# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
import time
import random
import d_server
import d_weather
import d_items

class Weather:
    def __init__(self):
        curTime = int(time.time())
        if self.weatherId <= 0:
            #新注册玩家
            self.weatherId = d_server.InitWeather
            self.weatherTime = curTime
            self.triggerDisaster(curTime)
        else:
            self.checkOfflineWeather(curTime)

    def changeWeather(self, curTime):
        # 检测天气变化
        # 首先使农作物当前灾害生效
        isEffect = self.effectDisaster()
        if isEffect:
            self.client.clearAllDisaster()
            self.updateToWatcher(d_server.UpdateType.ClearAllDisaster, {})
        # 随机产生新的天气
        self.weatherId = self.getRandWeather()
        self.weatherTime = curTime
        # 产生新天气时，检测灾害触发
        isTrigger = self.triggerDisaster(curTime)
        self.updateToWatcher(d_server.UpdateType.Weather, {})
        if isEffect or isTrigger:
            self.fieldList = self.fieldList
            self.updateToWatcher(d_server.UpdateType.FieldList, {})

    def checkWeather(self, curTime):
        if not self.client:
            return
        if curTime - self.weatherTime >= d_server.WeatherChangeSpace:
            self.changeWeather(curTime)
            return
        if curTime - self.disasterTime >= d_server.DisasterTriggerSpace:
            #检测灾害触发
            isTrigger = self.triggerDisaster(curTime)
            if isTrigger:
                self.fieldList = self.fieldList
                self.updateToWatcher(d_server.UpdateType.FieldList, {})

    def triggerDisaster(self, curTime):
        #触发一次自然灾害
        self.disasterTime = curTime
        self.checkDisaster()

    def getRandWeather(self):
        #随机获取一个天气
        totalRatio = 0
        for weatherData in d_weather.weather.values():
            totalRatio += weatherData["ratio"]
        randRes = random.randint(1, totalRatio)
        ratioSum = 0
        for weatherData in d_weather.weather.values():
            ratioSum += weatherData["ratio"]
            if randRes <= ratioSum:
                return weatherData["id"]
        return 1

    def checkOfflineWeather(self, curTime):
        #实体创建之后对离线天气数据的处理
        if curTime - self.disasterTime < d_server.DisasterTriggerSpace:
            return
        #天气没有改变
        offlineNextWeatherTime = self.weatherTime + d_server.WeatherChangeSpace
        if curTime < offlineNextWeatherTime:
            #触发一次灾害
            if self.checkDisaster():
                self.fieldList = self.fieldList
            return
        #天气发生变化
        #离线时已经存在的天气
        remainTriggerCount = (offlineNextWeatherTime - self.disasterTime) // d_server.DisasterTriggerSpace - 1
        if remainTriggerCount > 0:
            self.checkDisaster()
        #天气发生变化
        #离线时灾害生效
        for fieldData in self.fieldList:
            if fieldData["disasterId"] > 0:
                fieldData["disasterList"].append(fieldData["disasterId"])
                fieldData["disasterId"] = 0
        #后续完整度过的新天气，触发灾害并是灾害生效
        newWeatherCount = (curTime - offlineNextWeatherTime) // d_server.WeatherChangeSpace
        if newWeatherCount > 0:
            isHaveNoRipe = True
            tempTime = offlineNextWeatherTime
            for i in range(newWeatherCount):
                #每个完整度过的新天气，触发一次，触发几率按照次数翻倍
                weatherId = self.getRandWeather()
                retio = d_weather.weather[weatherId]["triggerratio"] * d_server.WeatherTriggerNum
                isHaveNoRipe = False
                for fieldData in self.fieldList:
                    if not self.isRipe(fieldData["index"], tempTime):
                        # 按照概率触发
                        isHaveNoRipe = True
                        randRes = random.randint(1, d_server.RandomBase)
                        if randRes <= retio:
                            fieldData["disasterList"].append(d_weather.weather[weatherId]["disaster"])
                tempTime += offlineNextWeatherTime
                if not isHaveNoRipe:
                    #如果所有的农作物都已经成熟，则直接设置当前天气，结束检测
                    self.weatherId = weatherId
                    self.fieldList = self.fieldList
                    return
        #后续不完整度过的新天气，触发一次灾害
        self.weatherId = self.getRandWeather()
        for fieldData in self.fieldList:
            if fieldData["disasterId"] <= 0:
                if not self.isRipe(fieldData["index"], curTime):
                    randRes = random.randint(1, d_server.RandomBase)
                    if randRes <= d_weather.weather[self.weatherId]["triggerratio"]:
                        fieldData["disasterId"] = d_weather.weather[self.weatherId]["disaster"]
        self.fieldList = self.fieldList